<?php

namespace backend\controllers;

use common\models\Admin;
use common\models\JurisdGroup;
use common\models\JurisdUser;
use common\models\Menu;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\LogaddService;
use common\service\MenuService;

class AdminController extends BaseController
{
    /**
     * 这里是登录界面.
     */
    public function actionLogin()
    {
        $this->layout = 'common';
        if($this->isGet())
        {
            return $this->render('login');
        }
        if($this->isPost() && $this->isAjax())
        {
            $data = $this->post();
            if(!array_key_exists('username',$data) || !array_key_exists('pass',$data)|| !array_key_exists('code',$data))
            {
                return $this->renderJson([],'信息不完整',ConstantService::$response_fail);
            }

//            if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$data['email']))
//            {
//                return $this->renderJson([],'请输入正确邮箱',ConstantService::$response_fail);
//            }
            if($this->_checkcaptcha($data['code']) !== true){
                return $this->renderJson([],'验证码错误!',ConstantService::$response_fail);

            }

            // 开始登录.
            $admin_user = Admin::findOne(['username'=>$data['username']]);

            if(!$admin_user)
            {
                return $this->renderJson([],'登录失败,请检查所输入的用户名和密码!',ConstantService::$response_fail);
            }

            // 开始验证正确的密码.
            if($admin_user['password'] != md5(md5($data['pass']).$this->salt))
            {
                return $this->renderJson([],'登录失败,请检查所输入的用户名和密码!',ConstantService::$response_fail);
            }

            // 这里开始其他操作.记住用户的密码.
            $token = $admin_user->primaryKey . '#' . $this->genToken($admin_user);
            $this->addCookie($this->auth_cookie, $token,7200);
            $admin_user->setAttributes([
                'last_ip'   => CommonService::getIP(),
                'last_time' => date('Y-m-d H:i:s')
            ]);
            $admin_user->save(0);
            $str = $admin_user['username'].'在'.date("Y-m-d H:i:s").'登录成功!';
            LogaddService::logAdd($admin_user['username'],$str);

            return $this->renderJson([],'登录成功',ConstantService::$response_success);
        }

        return $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
    }

    private function _checkcaptcha($code){
        $current_code = $this->getCookie($this->cookie_captcha_name);
        if($current_code && $current_code == $code){
            return true;
        }
        return false;
    }

    /**
     * 用户退出.
     */
    public function actionLogout()
    {
        $this->removeCookie($this->auth_cookie);
        return $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
    }

    /**
     * 管理员列表 TODO 这个地方查询需要修改,效率太低
     */
    public function actionIndex(){
        if($this->isAjax() && $this->isGet()){
            $p = intval( $this->get('page',1) );
            $this->page_size = intval( $this->get('limit',10) );
            $p = ( $p > 0 )? $p : 1;
            $admin_query = Admin::find();
            $count = $admin_query->count();

            $offset = ($p - 1) * $this->page_size;

            $list = $admin_query->orderBy(['id' => SORT_DESC])
                ->offset( $offset )
                ->limit( $this->page_size )
                ->asArray()
                ->all();

            foreach ($list as &$admin){
                $roleids = JurisdUser::find()->where(['admin_id'=>$admin['id']])->asArray()->all();
                if(!empty($roleids)){
                    $roles = JurisdGroup::find()->where(['group_id'=>array_column($roleids,'group_id')])->asArray()->all();
                    $admin['role'] = implode(array_column($roles,'group_name'),',');
                }
                elseif($admin['id'] == 1)
                {
                    $admin['role'] = '全部';
                }else{
                    $admin['role'] = '';
                }
            }
            return $this->renderPageJson($list,$count,ConstantService::$response_tab_success);
        }
        return $this->render('index');
    }

    /**
     * 新增管理员
     */
    public function actionAddAdmin(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $admin_model = new Admin();
            $row = Admin::find()->where(['username'=>$data['username']])->one();
            if(!empty($row)){
                return $this->renderJson([],'已经存在同名管理员',ConstantService::$response_fail);
            }
            if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$data['email']))
            {
                return $this->renderJson([],'请输入正确邮箱',ConstantService::$response_fail);
            }
            $role_ids = $data['role_ids'];

            unset($data['role_ids']);
            $data['password'] = md5(md5($data['password']).$this->salt);
            $data['created_time'] = date("Y-m-d H:i:s");
            $data['last_time'] = date("Y-m-d H:i:s");
            $data['updated_time'] = date("Y-m-d H:i:s");
            $admin_model->setAttributes($data);
            $ex = $admin_model->save();
            if($ex){
                $admin_id = \Yii::$app->db->getLastInsertID();
                $arr = [];
                if(!empty($role_ids)){
                    foreach ($role_ids as $role_id){
                        $arr[] = ['admin_id'=>$admin_id,'group_id'=>$role_id,'user_mech'=>1,'created_at'=>time()];
                    }
                }
                //存储用户和角色关系
//                ModelName::getDb()->createCommand()->batchInsert(表名,表的列名数组,要插入的二维数组数据)->execute();
                $re = Admin::getDb()->createCommand()->batchInsert('jurisd_user',['admin_id','group_id','user_mech','created_at'],$arr)->execute();
                if($re){
                    $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'新增管理员'.$data['username'];
                    LogaddService::logAdd($this->admin['username'],$str);
                    return $this->renderJson([],'新增成功',ConstantService::$response_success);
                }

            }
            return $this->renderJson([],'添加失败',ConstantService::$response_fail);

        }
        $perms = JurisdGroup::find()->asArray()->all();
        return $this->render('add-admin',['perms'=>$perms]);
    }

    /**
     * 修改管理员
     */
    public function actionUpdateAdmin(){
        if($this->isPost() && $this->isPost()){
            $data = $this->post();
            $row = Admin::findOne(['username'=>$data['username']]);
            if(!empty($row) && $row['id'] != $data['id']){
                return $this->renderJson([],'已经存在同名管理员',ConstantService::$response_fail);
            }
            if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$data['email']))
            {
                return $this->renderJson([],'请输入正确邮箱',ConstantService::$response_fail);
            }
            $role_ids = $data['role_ids'];
            unset($data['role_ids']);
            if(!empty($data['password'])){
                $data['password'] = md5(md5($data['password']).$this->salt);
            }else{
                unset($data['password']);
            }
            $data['updated_time'] = date("Y-m-d H:i:s");
            $admin = Admin::findOne(['id'=>$data['id']]);
            $admin->setAttributes($data);
            if($admin->save()){
                JurisdUser::deleteAll(['admin_id'=>$data['id']]);
                $arr = [];
                foreach ($role_ids as $role_id){
                    $arr[] = ['admin_id'=>$data['id'],'group_id'=>$role_id,'user_mech'=>1,'created_at'=>time()];
                }
                $re = Admin::getDb()->createCommand()->batchInsert('jurisd_user',['admin_id','group_id','user_mech','created_at'],$arr)->execute();
                if($re){
                    $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改管理员'.$data['username'];
                    LogaddService::logAdd($this->admin['username'],$str);
                    return $this->renderJson([],'修改成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'修改失败,请稍后再试',ConstantService::$response_fail);
            }
            return $this->renderJson([],'修改失败,请稍后再试',ConstantService::$response_fail);
        }

        $id = $this->get('id');
        $admin = Admin::find()->where(['id'=>$id])->asArray()->one();
        $current_roles = JurisdUser::find()->where(['admin_id'=>$id])->asArray()->all();
        $roles = array_column($current_roles,'group_id');
        $perms = JurisdGroup::find()->asArray()->all();
        return $this->render('update-admin',['admin'=>$admin,'roles'=>$roles,'perms'=>$perms]);

    }

    /**
     * 删除管理员
     */
    public function actionDelAdmin(){
        if($this->isAjax() && $this->isPost()){
            $id = $this->post('id');
            $admin = Admin::find()->where(['id'=>$id])->one();
            if($admin->delete()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'删除管理员'.$admin['username'];
                LogaddService::logAdd($this->admin['username'],$str);

//                JurisdUser::deleteAll(['admin_id'=>$id]);
                JurisdUser::deleteAll('admin_id=:admin_id',['admin_id'=>$id]);
                return $this->renderJson([],'删除成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'删除失败,请稍后再试',ConstantService::$response_fail);

        }
        return $this->renderJson([],'参数不合法',ConstantService::$response_fail);

    }

    /**
     * 修改密码
     */
    public function actionModifyPwd(){
        //前台页面使用弹窗 id 原密码 ,新密码,确认密码
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $admin = Admin::findOne(['id'=>$this->admin['id']]);
            if($admin['password'] == md5(md5($data['pwd']).$this->salt)){
                return $this->renderJson([],'原密码和新密码一致',ConstantService::$response_fail);
            }
            if($data['pwd'] != $data['re_pwd']){
                return $this->renderJson([],'两次输入密码不一致',ConstantService::$response_fail);
            }
            $admin['password'] = md5(md5($data['pwd']).$this->salt);
            if($admin->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改密码为'.$data['pwd'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'修改失败,请稍后再试',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    public function actionGetInfo(){
        $id = $this->admin['id'];
        $admin = Admin::find()->where(['id'=>$id])->asArray()->one();
        $menus = Menu::find()->asArray()->all();

        if($id != 1){
            $current_roles = JurisdUser::find()->where(['admin_id'=>$id])->asArray()->all();
            $group_id = array_column($current_roles,'group_id');
            $row = JurisdGroup::find()->where(['group_id'=>$group_id])->asArray()->one();
            if(!empty($row['group_jurisd_id'])){
                $menu_ids = explode(',',$row['group_jurisd_id']);
            }else{
                $menu_ids = [];
            }
        }else{
        $menu_ids = array_column($menus,'menu_id');
        }


        $menus = MenuService::addCheckStatus($menus,$menu_ids);
        $current_perms = MenuService::getCategory($menus);
        return $this->render('get-info',['admin'=>$admin,'perms'=>$current_perms]);

    }


}